package com.penghaisoft.microwms.material.web.intowarehouse.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.penghaisoft.microwms.common.Constant;
import com.penghaisoft.microwms.common.base.model.BaseDictionary;
import com.penghaisoft.microwms.common.dto.TransResult;
import com.penghaisoft.microwms.common.page.Pager;
import com.penghaisoft.microwms.common.service.BaseService;
import com.penghaisoft.microwms.common.wms.model.MSBarCode;
import com.penghaisoft.microwms.common.wms.model.RawAuditingHis;
import com.penghaisoft.microwms.common.wms.model.RawBack;
import com.penghaisoft.microwms.common.wms.model.RawBarcode;
import com.penghaisoft.microwms.common.wms.model.RawCarCheckIn;
import com.penghaisoft.microwms.common.wms.model.RawContractChange;
import com.penghaisoft.microwms.common.wms.model.RawStorageSn;
import com.penghaisoft.microwms.material.web.insidewarehouse.dao.BaseDictionaryMapper;
import com.penghaisoft.microwms.material.web.insidewarehouse.dao.RawContractChangeMapper;
import com.penghaisoft.microwms.material.web.insidewarehouse.dao.RawStorageSnMapper;
import com.penghaisoft.microwms.material.web.intowarehouse.dao.MSBarCodeMapper;
import com.penghaisoft.microwms.material.web.intowarehouse.dao.RawAuditingHisMapper;
import com.penghaisoft.microwms.material.web.intowarehouse.dao.RawBarcodeMapper;
import com.penghaisoft.microwms.material.web.intowarehouse.dao.RawCarCheckInMapper;
import com.penghaisoft.microwms.material.web.intowarehouse.service.IMaterialIntoService;
import com.penghaisoft.microwms.material.web.outwarehouse.dao.RawBackMapper;



/**
 * @Description 原材料入库
 * @author luoteng
 * @date 2018年5月23日 上午11:47:37
 * @version 1.0
 */
@Service("materialIntoService")
public class MaterialIntoServiceImpl extends BaseService implements
		IMaterialIntoService {
	@Resource
	private RawBarcodeMapper rawBarcodeMapper;
	
	@Resource
	private RawStorageSnMapper rawStorageSnMapper;
	
	@Resource
	private MSBarCodeMapper mSBarCodeMapper;
	
	@Resource 
	private RawCarCheckInMapper rawCarCheckInMapper;
	
	@Resource
	private RawAuditingHisMapper rawAuditingHisMapper;
	
	@Resource
	private BaseDictionaryMapper baseDictionaryMapper;
	
	@Autowired
	private RawContractChangeMapper rawContractChangeMapper;
    
    @Autowired
    private RawBackMapper rawBackMapper;
	
	/** 
	 * @Title findListByCondition
	 * @Description 原材料条码查询列表
	 * @author luoteng
	 * @date 2018年5月23日:上午11:58:10
	 * @param page
	 * @param rows
	 * @param condition
	 * @return
	 */
	@Override
	public Pager<RawBarcode> findListByCondition(int page, int rows, RawBarcode condition) {
		Pager<RawBarcode> pager = new Pager<>();
		pager.setPage(page);
		pager.setRows(rows);
//		condition.preQuery();
		List<RawBarcode> records = new ArrayList<RawBarcode>();
		long size = rawBarcodeMapper.queryCount(condition);
		if(size > 0){
			records = rawBarcodeMapper.queryList(pager, condition);
		}
		pager.setRecords(records);
		pager.setTotalCount(size);
		return pager;
	}
	
	/** 
	 * @Title createBarcode
	 * @Description 条码新增
	 * @author luoteng
	 * @date 2018年5月23日:下午5:34:38
	 * @param condition
	 * @return int
	 */
	@Override
	public int createBarcode(RawBarcode condition){
		return rawBarcodeMapper.create(condition);
	}
	
	/** 
	 * @Title createBarcodeByList
	 * @Description 条码新增【批量】
	 * @author luoteng
	 * @date 2018年7月2日:下午3:53:03
	 * @param condition
	 * @param barcodeList
	 */
	@Override
	@Transactional
	public void createBarcodeByList(RawBarcode condition, List<String> barcodeList){
		for(String barCode : barcodeList){
			condition.setBarcode(barCode);
			rawBarcodeMapper.create(condition);
			
			MSBarCode record = new MSBarCode();
			record.setBarCode(condition.getBarcode());
			record.setModelCode(condition.getModel());
			record.setModelType(condition.getModelType());
			record.setContractNo(condition.getContractNo());
			record.setSpecification(condition.getAmount().toString());
			record.setUpdateDate(condition.getGmtCreate());
//			条码打印接口表
			mSBarCodeMapper.insertSelective(record);
		}
	}
	
	/** 
	 * @Title updateBarcode
	 * @Description 条码修改
	 * @author luoteng
	 * @date 2018年5月23日:下午5:34:47
	 * @param condition
	 * @return int
	 */
	@Override
	public int updateBarcode(RawBarcode condition){
		return rawBarcodeMapper.updateBySelect(condition);
	}
	
	/** 
	 * @Title updateBarcodeRelate
	 * @Description 条码修改【对应修改接口表】
	 * @author luoteng
	 * @date 2018年7月2日:下午5:25:15
	 * @param condition
	 */
	@Override
	public void updateBarcodeRelate(RawBarcode condition){
		rawBarcodeMapper.updateBySelect(condition);
		
		MSBarCode record = new MSBarCode();
		record.setBarCode(condition.getBarcode());
		// 有效标志 1-有效 0-无效
		if(condition.getActiveFlag() != null && condition.getActiveFlag().equals("0")){
			mSBarCodeMapper.deleteByBarcode(record);
		}else{
			record.setSpecification(condition.getAmount().toString());
			record.setUpdateDate(condition.getGmtCreate());
//			条码打印接口表
			mSBarCodeMapper.updateByBarcodeSelective(record);
		}
	}
	
	/** 
	 * @Title getBarcodeList
	 * @Description 获取条码数组
	 * @author luoteng
	 * @date 2018年5月23日:下午5:54:30
	 * @param condition
	 * @return List<RawBarcode>
	 */
	@Override
	public List<RawBarcode> getBarcodeList(RawBarcode condition){
		return rawBarcodeMapper.queryByAny(condition);
	}
	
	/** 
	 * @Title findIntoWhRawStorageSnList
	 * @Description 查询入库条码明细
	 * @author luoteng
	 * @date 2018年5月24日:下午4:17:47
	 * @param page
	 * @param rows
	 * @param condition
	 * @return Pager<RawStorageSn>
	 */
	@Override
	public Pager<RawStorageSn> findIntoWhRawStorageSnList(int page, int rows, RawStorageSn condition){
		Pager<RawStorageSn> pager = new Pager<>();
		pager.setPage(page);
		pager.setRows(rows);
//		退扫的不查询出来
		condition.preQuery();
//		查询入库明细 amout>0
		condition.setAmountUpZero("UpZero");
		List<RawStorageSn> records = new ArrayList<RawStorageSn>();
		long size = rawStorageSnMapper.queryCount(condition);
		if(size > 0){
			records = rawStorageSnMapper.queryList(pager, condition);
			
			RawStorageSn sumAmount = rawStorageSnMapper.querySumAmount(condition);
			pager.setOrder("{\"amount\":\"" + sumAmount.getAmount() + "\"}");
		}
		pager.setRecords(records);
		pager.setTotalCount(size);
		return pager;
	}
	
	/** 
	 * @Title listIntoWhModelType
	 * @Description 查询入库型号明细
	 * @author luoteng
	 * @date 2018年5月24日:下午4:17:47
	 * @param page
	 * @param rows
	 * @param condition
	 * @return Pager<RawStorageSn>
	 */
	@Override
	public Pager<RawStorageSn> listIntoWhModelType(int page, int rows, RawStorageSn condition){
		Pager<RawStorageSn> pager = new Pager<>();
		pager.setPage(page);
		pager.setRows(rows);
		
		List<RawStorageSn> records = new ArrayList<RawStorageSn>();
		long size = rawStorageSnMapper.countIntoWhModelType(condition);
		if(size > 0){
			records = rawStorageSnMapper.listIntoWhModelType(pager, condition);
		}
		pager.setRecords(records);
		pager.setTotalCount(size);
		return pager;
	}

	/* @Title: findIntoWhList 
	 * @Description: 原材料入库明细导出 
	 * @author jzh
	 * @date 2018年10月8日 上午10:08:23 
	 */
	@Override
	public List<RawStorageSn> findIntoWhList(RawStorageSn condition) {
//		退扫的不查询出来
		condition.preQuery();
//		查询入库明细 amout>0
		condition.setAmountUpZero("UpZero");
		List<RawStorageSn> records = rawStorageSnMapper.queryList(null, condition);
		return records;
	}
	
	/* @Title: findListAuditing 
	 * @Description: 原材料退扫审核列表查询
	 * @author lengxf
	 */
	@Override
	public Pager<RawStorageSn> findListAuditing(int page, int rows, RawStorageSn condition){
		Pager<RawStorageSn> pager = new Pager<>();
		pager.setPage(page);
		pager.setRows(rows);
		
		List<RawStorageSn> records = new ArrayList<RawStorageSn>();
		long size = rawStorageSnMapper.countAuditing(condition);
		if(size > 0){
			records = rawStorageSnMapper.listAuditing(pager, condition);
		}
		pager.setRecords(records);
		pager.setTotalCount(size);
		return pager;
	}
	
	
	@Override
	public Pager<RawAuditingHis> findListAuditingHis(int page, int rows, RawAuditingHis condition){
		Pager<RawAuditingHis> pager = new Pager<>();
		pager.setPage(page);
		pager.setRows(rows);
		
		List<RawAuditingHis> records = new ArrayList<RawAuditingHis>();
		long size = rawAuditingHisMapper.queryCount(condition);
		if(size > 0){
			records = rawAuditingHisMapper.queryList(pager, condition);
		}
		pager.setRecords(records);
		pager.setTotalCount(size);
		return pager;
	}
	
	@Override
	public RawStorageSn findByStroageSnId(RawStorageSn rawStorageSn){
		return rawStorageSnMapper.queryBySnId(rawStorageSn);
	}
	
	@Transactional
	@Override
	public TransResult delBarcode(RawStorageSn rawStorageSn , String loginNmae){
		Date now = new Date();
		TransResult result = new TransResult();
        result.setCode(Constant.SUCCESS);
        
        RawStorageSn upob = rawStorageSnMapper.queryBySnId(rawStorageSn);
        
//    	0可用；1 冻结；2已出库 3 报废
    	if("2".equals(upob.getBarcodeStatus())){
    		result.setCode(Constant.FAIL);
            result.setMsg("该条码已出库 ，不能审核!");
            return result;
    	}else if("3".equals(upob.getBarcodeStatus())){
    		result.setCode(Constant.FAIL);
            result.setMsg("该条码已报废，不能审核!");
            return result;
    	}
        
        RawBack back = new RawBack();
    	back.setBarcode(rawStorageSn.getBarcode());
    	back.setActiveFlag("1");
    	
    	List<RawBack> bkList = rawBackMapper.queryByAny(back);
    	if(bkList != null && !bkList.isEmpty()) {
    		for(RawBack bk : bkList) {
    			BigDecimal oldAmount = bk.getOldAmount() == null ? BigDecimal.ZERO : bk.getOldAmount();
    			BigDecimal amount = bk.getAmount() == null ? BigDecimal.ZERO : bk.getAmount();
    			if(oldAmount.compareTo(amount) != 0) {
    				result.setCode(Constant.FAIL);
                    result.setMsg("该条码发生过生产退料，且长度已改变，不能审核!");
                    return result;
    			}
    		}
    	}
    	
    	RawContractChange rawContractChange = new RawContractChange();
    	rawContractChange.setBarcode(rawStorageSn.getBarcode());
    	rawContractChange.setActiveFlag("1");
    	
    	List<RawContractChange> contractChangeList = rawContractChangeMapper.queryByAny(rawContractChange);
    	if(contractChangeList != null && !contractChangeList.isEmpty()) {
    		result.setCode(Constant.FAIL);
            result.setMsg("该条码发生过合同借用，不能审核!");
            return result;
    	}
        
        if("1".equals(rawStorageSn.getUserDefined4())){
	    	RawBarcode rawBarcode = new RawBarcode();
	        rawBarcode.setBarcode(rawStorageSn.getBarcode());
	        rawBarcode.setActiveFlag("1");
	        List<RawBarcode> barList = rawBarcodeMapper.queryByAny(rawBarcode);
	        if(barList != null && !barList.isEmpty()){
	        	RawBarcode tmp = barList.get(0);
	//        	入库状态：0 未入库 1已入库
	        	tmp.setUserDefined1("0");
	        	tmp.setLastModifiedBy(loginNmae);
	        	tmp.setGmtModified(now);
	//        	是否合格：0-不合格 1-合格
	        	tmp.setUserDefined6("1");
	//        	不合格原因
	        	tmp.setUserDefined7(" ");
	        	rawBarcodeMapper.updateBySelect(tmp);
	        	
	        	RawCarCheckIn rawCarCheckIn = new RawCarCheckIn();
	        	rawCarCheckIn.setCheckInNo(tmp.getUserDefined2());
	        	rawCarCheckIn.setModel(tmp.getModel());
	        	rawCarCheckIn.setActiveFlag("1");
	        	List<RawCarCheckIn> ckInList = rawCarCheckInMapper.queryByAny(rawCarCheckIn);
	        	if(ckInList != null && !ckInList.isEmpty()){
	        		RawCarCheckIn upOb = new RawCarCheckIn();
	        		upOb.setCheckInId(ckInList.get(0).getCheckInId());
	        		upOb.setInAmountDel(1);
	        		upOb.setLastModifiedBy(loginNmae);
	        		upOb.setGmtModified(now);
	        		rawCarCheckInMapper.updateBySelect(upOb);
	        	}	
	        }
        }
        
        //'审核状态 0 审核中 1 审核通过 2审核不通过',
        if("1".equals(rawStorageSn.getUserDefined4())){
        	upob.setActiveFlag("0");
        	upob.setLastModifiedBy(loginNmae);
        	upob.setGmtModified(now);
        	upob.setUserDefined4(rawStorageSn.getUserDefined4());
        	
        	RawAuditingHis entity = new RawAuditingHis();
        	entity.setLastModifiedBy(loginNmae);
        	entity.setGmtModified(now);
        	entity.setContractNo(upob.getContractNo());
        	entity.setBarcode(upob.getBarcode());
        	//'审核状态 0 审核中 1 审核通过 2审核不通过',
        	entity.setAuditingStatus(rawStorageSn.getUserDefined4());
        	//临时存放审核备注
        	entity.setAuditingRemark(rawStorageSn.getUserDefined10());
        	entity.setModel(upob.getModel());
        	entity.setModelDesc(upob.getModelDesc());
        	entity.setModelType(upob.getModelType());
        	entity.setUserDefined3(upob.getUserDefined3());
        	entity.setUnit(upob.getUnit());
        	entity.setAmount(upob.getAmount());
        	entity.setBarcodeStatus(upob.getBarcodeStatus());
        	entity.setWlCode(upob.getWlCode());
        	entity.setGmtCreate(upob.getGmtModified());
        	entity.setActiveFlag("1");
        	entity.setCreateBy(upob.getUserDefined5());//创建人字段记录请求发起者，即sn表的UserDefined5
        	rawAuditingHisMapper.create(entity);
        }else if("2".equals(rawStorageSn.getUserDefined4())){
        	upob.setLastModifiedBy(loginNmae);
        	upob.setGmtModified(now);
        	upob.setUserDefined4(rawStorageSn.getUserDefined4());
        	//退扫审核不通过时，把状态置为可用
        	upob.setBarcodeStatus("0");
        	
        	RawAuditingHis entity = new RawAuditingHis();
        	entity.setLastModifiedBy(loginNmae);
        	entity.setGmtModified(now);
        	entity.setContractNo(upob.getContractNo());
        	entity.setBarcode(upob.getBarcode());
        	//'审核状态 0 审核中 1 审核通过 2审核不通过',
        	entity.setAuditingStatus(rawStorageSn.getUserDefined4());
        	//临时存放审核备注
        	entity.setAuditingRemark(rawStorageSn.getUserDefined10());
        	entity.setModel(upob.getModel());
        	entity.setModelDesc(upob.getModelDesc());
        	entity.setModelType(upob.getModelType());
        	entity.setUserDefined3(upob.getUserDefined3());
        	entity.setUnit(upob.getUnit());
        	entity.setAmount(upob.getAmount());
        	entity.setBarcodeStatus(upob.getBarcodeStatus());
        	entity.setWlCode(upob.getWlCode());
        	entity.setGmtCreate(upob.getGmtModified());
        	entity.setActiveFlag("1");
        	entity.setCreateBy(upob.getUserDefined5());//创建人字段记录请求发起者，即sn表的UserDefined5
        	rawAuditingHisMapper.create(entity);
        }
        rawStorageSnMapper.updateBySelect(upob);
        return result;
	}
	
	
	/**  
	 * @Title: findQuantitiyWbMaterial
	 * @Description:   接口-查询黑白料库存
	 * @author Lengxf  
	 * @date 2019年3月8日    
	 */  
	@Override
	public RawStorageSn findQuantitiyWbMaterial(RawStorageSn rawStorageSn){
		RawStorageSn result = rawStorageSnMapper.findQuantitiyWbMaterial(rawStorageSn);
		if(result == null){
			result = new RawStorageSn();
			result.setWhiteStockQuantitiy(0);
			result.setBlackStockQuantitiy(0);
		}
		return result;
	}
	
	/**  
	 * @Title: findQuantitiyMaterial
	 * @Description:   接口-原材料库存
	 * @author Lengxf  
	 * @date 2019年3月8日    
	 */  
	@Override
	public Pager<RawStorageSn> findQuantitiyMaterial(int page, int rows, RawStorageSn condition){
		Pager<RawStorageSn> pager = new Pager<>();
		pager.setPage(page);
		pager.setRows(rows);
		List<RawStorageSn> records = new ArrayList<RawStorageSn>();
		long size = rawStorageSnMapper.countQuantitiyMaterial(condition);
		if(size > 0){
			records = rawStorageSnMapper.findQuantitiyMaterial(pager, condition);
		}
		pager.setRecords(records);
		pager.setTotalCount(size);
		return pager;
	}
	
	
	/**  
	 * @Title: findQuantitiyMaterialToSn
	 * @Description:   接口-原材料库存明细
	 * @author Lengxf  
	 * @date 2019年3月11日    
	 */ 
	@Override
	public Pager<RawStorageSn> findQuantitiyMaterialToSn(int page, int rows, RawStorageSn condition){
		
		List<BaseDictionary> modelTypeList = baseDictionaryMapper.queryDicTypeModelType();
		if(condition.getMaterialName() != null && !"".equals(condition.getMaterialName())){
			if(modelTypeList != null && modelTypeList.size() > 0){
				for(BaseDictionary tmp : modelTypeList){
					if(condition.getMaterialName().equals(tmp.getDicName())){
						condition.setMaterialName(tmp.getDicCode());
					}
				}
			}
		}
		
		Pager<RawStorageSn> pager = new Pager<>();
		pager.setPage(page);
		pager.setRows(rows);
		List<RawStorageSn> records = new ArrayList<RawStorageSn>();
		long size = rawStorageSnMapper.countQuantitiyMaterialToSn(condition);
		if(size > 0){
			records = rawStorageSnMapper.findQuantitiyMaterialToSn(pager, condition);
		}
		pager.setRecords(records);
		pager.setTotalCount(size);
		return pager;
	}
	
	/**  
	 * @Title: findQuantitiyMaterialInTime
	 * @Description:   手机APP接口-展示原材料超期、未超期库存
	 * @author Lengxf  
	 * @date 2019年3月18日    
	 */  
	public List<RawStorageSn> findQuantitiyMaterialInTime(RawStorageSn condition){
		return rawStorageSnMapper.findQuantitiyMaterialInTime(condition);
	}
	
	
}
